<?php
declare(strict_types=1);

namespace App\Wxc\Service;

use App\Wxc\Mapper\WxcSharerLevelMapper;
use App\Wxc\Request\WxcSharerLevelSaveRequest;
use App\Wxc\Request\WxcSharerLevelSortRequest;
use Exception;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;

/**
 * 分享员身份等级服务
 */
class WxcSharerLevelService extends AbstractService
{
    /**
     * @var WxcSharerLevelMapper
     */
    public $mapper;


    public function __construct(WxcSharerLevelMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function saveLevel(WxcSharerLevelSaveRequest $input): mixed
    {
        if (!is_int($input->sort_id)) {
            $maxLevel = $this->mapper->getMaxLevel();
            if ($maxLevel) {
                $sortId = $maxLevel->sort_id + 1;
            } else {
                $sortId = 1;
            }
        } else {
            $sortId = $input->sort_id;
        }

        // 根据title判断是否已存在
        $level = $this->mapper->first(['title' => $input->title, 'sort_id' => $sortId]);
        if ($level) {
            throw new Exception('等级已存在：' . $input->title);
        }

        $info = $input->toArray();
        $info['sort_id'] = $sortId;

        return $this->mapper->save($info);
    }

    // 等级排序
    public function sort(WxcSharerLevelSortRequest $input): bool
    {
        Db::transaction(function () use ($input) {
            foreach ($input->items as $item) {
                $level = $this->mapper->first(['level_id' => $item->level_id]);
                if ($level) {
                    $level->sort_id = $item->sort_id;
                    $level->save();
                }
            }
        });
        return true;
    }
}